package com.itheima.service.Impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzLeaveException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Service
@Transactional
public class ClazzServiceImpl implements ClazzService {
    @Autowired
     private ClazzMapper clazzMapper;
    @Autowired
     private StudentMapper studentMapper;
    @Override   //班级主页 分页查询
    public PageBean clazzList(ClazzQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Clazz> clazzList = clazzMapper.clazzList(param);
        //解析封装分页结果
        Page<Clazz> p =(Page<Clazz>) clazzList;
        return new PageBean(p.getTotal(),p.getResult());
    }
    @Override
    public void add(Clazz clazz) {
         clazz.setCreateTime(LocalDateTime.now());
         clazz.setUpdateTime(LocalDateTime.now());
         clazzMapper.add(clazz);
    }
    @Override
    public Clazz selectById(Integer id) {
        return clazzMapper.selectById(id);
    }
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
    @Override
    public void delete(Integer id) {
        Integer countId = studentMapper.countClazzId(id);
        if (countId != 0) {
            throw new ClazzLeaveException("该班级下有学生，不能删除！");
        }
        clazzMapper.delete(id);
    }

    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }
}
